//package com.letu.database.plugins;
//
//import com.baomidou.mybatisplus.core.parser.SqlParserHelper;
//import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
//import com.baomidou.mybatisplus.core.toolkit.*;
//import com.baomidou.mybatisplus.extension.parser.JsqlParserSupport;
//import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
//import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
//import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
//import com.baomidou.mybatisplus.extension.toolkit.PropertyMapper;
//import com.letu.core.businmodel.TenantIgnoreTable;
//import com.letu.core.context.ContextUtil;
//import com.letu.core.context.StaticContextUtil;
//import com.letu.core.handler.DataScopeHandler;
//import com.letu.core.model.DataScopeEnum;
//import lombok.extern.slf4j.Slf4j;
//import net.sf.jsqlparser.expression.*;
//import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
//import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
//import net.sf.jsqlparser.expression.operators.relational.*;
//import net.sf.jsqlparser.schema.Column;
//import net.sf.jsqlparser.schema.Table;
//import net.sf.jsqlparser.statement.delete.Delete;
//import net.sf.jsqlparser.statement.insert.Insert;
//import net.sf.jsqlparser.statement.select.*;
//import net.sf.jsqlparser.statement.update.Update;
//import org.apache.ibatis.executor.Executor;
//import org.apache.ibatis.executor.statement.StatementHandler;
//import org.apache.ibatis.mapping.BoundSql;
//import org.apache.ibatis.mapping.MappedStatement;
//import org.apache.ibatis.mapping.SqlCommandType;
//import org.apache.ibatis.session.ResultHandler;
//import org.apache.ibatis.session.RowBounds;
//
//import java.sql.Connection;
//import java.sql.SQLException;
//import java.util.List;
//import java.util.Properties;
//
///**
// * 数据租户模式 在系统级别做租户模式（团队，系统级别）
// * 获取动态表名
// *
// * @author ligang
// * @date 2022/12/09 上午10:00
// */
//@Slf4j
//public class SystemTenantInnerInterceptor extends JsqlParserSupport implements InnerInterceptor {
//    //    private TenantLineHandler tenantLineHandler;
//    @Override
//    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
//        if (!InterceptorIgnoreHelper.willIgnoreTenantLine(ms.getId())) {
//            if (ContextUtil.getIsSystemOlationIgnore() != null && ContextUtil.getIsSystemOlationIgnore()) {
//                //忽略多租户模式，说明查询项目数据
//                return;
//            }
//            //是否在MybatisTenantLineHandler忽略了多租户
//            if (ContextUtil.getIsSystemTenantIgnore() != null && ContextUtil.getIsSystemTenantIgnore()) {
//                //忽略多租户模式，说明查询项目数据
//                return;
//            }
////            if (!SqlParserHelper.getSqlParserInfo(ms)) {
//            PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
//            String sql = this.parserSingle(mpBs.sql(), (Object) null);
//            mpBs.sql(sql);
////            }
//        }
//    }
//
//    @Override
//    public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
//        PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);
//        MappedStatement ms = mpSh.mappedStatement();
//        SqlCommandType sct = ms.getSqlCommandType();
//        if (sct == SqlCommandType.INSERT || sct == SqlCommandType.UPDATE || sct == SqlCommandType.DELETE) {
//            if (InterceptorIgnoreHelper.willIgnoreTenantLine(ms.getId())) {
//                return;
//            }
//
//            if (SqlParserHelper.getSqlParserInfo(ms)) {
//                return;
//            }
//            PluginUtils.MPBoundSql mpBs = mpSh.mPBoundSql();
////            log.info("before sql is {}", mpBs.sql());
//            String sql = this.parserMulti(mpBs.sql(), (Object) null);
////            log.info("after sql is {}", sql);
//            mpBs.sql(sql);
//        }
//
//    }
//
//    @Override
//    protected void processSelect(Select select, int index, String sql, Object obj) {
//        this.processSelectBody(select.getSelectBody());
//        List<WithItem> withItemsList = select.getWithItemsList();
//        if (!CollectionUtils.isEmpty(withItemsList)) {
//            withItemsList.forEach(this::processSelectBody);
//        }
//
//    }
//
//    protected void processSelectBody(SelectBody selectBody) {
//        if (selectBody != null) {
//            if (selectBody instanceof PlainSelect) {
//                this.processPlainSelect((PlainSelect) selectBody);
//            } else if (selectBody instanceof WithItem) {
//                WithItem withItem = (WithItem) selectBody;
//                this.processSelectBody(withItem.getSelectBody());
//            } else {
//                SetOperationList operationList = (SetOperationList) selectBody;
//                if (operationList.getSelects() != null && operationList.getSelects().size() > 0) {
//                    operationList.getSelects().forEach(this::processSelectBody);
//                }
//            }
//
//        }
//    }
//
//    @Override
//    protected void processInsert(Insert insert, int index, String sql, Object obj) {
//
//    }
//
//    @Override
//    protected void processUpdate(Update update, int index, String sql, Object obj) {
//        Table table = update.getTable();
//        //有的表不需要多租户
////        if(!TenantIgnoreTable.baseTable.contains(table.getName())){
////            update.setWhere(this.andExpression(table, update.getWhere()));
////        }
//
//        if (ContextUtil.getIsSystemOlationIgnore() != null && ContextUtil.getIsSystemOlationIgnore()) {
//            //忽略多租户模式，说明查询项目数据
//            return;
//        }
//        if (ContextUtil.getIsSystemTenantIgnore() != null && ContextUtil.getIsSystemTenantIgnore()) {
//            //忽略多租户模式，说明查询项目数据
//            return;
//        }
//
//        update.setWhere(this.andExpression(table, update.getWhere()));
//    }
//
//    @Override
//    protected void processDelete(Delete delete, int index, String sql, Object obj) {
//        if (ContextUtil.getIsSystemOlationIgnore() != null && ContextUtil.getIsSystemOlationIgnore()) {
//            //忽略多租户模式，说明查询项目数据
//            return;
//        }
//        if (ContextUtil.getIsSystemTenantIgnore() != null && ContextUtil.getIsSystemTenantIgnore()) {
//            //忽略多租户模式，说明查询项目数据
//            return;
//        }
////        if (!this.tenantLineHandler.ignoreTable(delete.getTable().getName())) {
////            delete.setWhere(this.andExpression(delete.getTable(), delete.getWhere()));
////        }
//        delete.setWhere(this.andExpression(delete.getTable(), delete.getWhere()));
//    }
//
//    protected BinaryExpression andExpression(Table table, Expression where) {
//        EqualsTo equalsTo = new EqualsTo();
//        equalsTo.setLeftExpression(this.getAliasColumn(table));
//        //数据隔离级别
//        String tableName = table.getName();
//        String columnStr = DataScopeHandler.queryTenantField(DataScopeHandler.queryTenantSystemScope(tableName));
//        if (isEqualsNoNull(tableName)) {
//            //值为空，则不走判断
//            equalsTo.setLeftExpression(new Column("project_id"));
//            equalsTo.setRightExpression(new LongValue(ContextUtil.getProjectId()));
//        } else {
//            equalsTo.setRightExpression(new LongValue(ContextUtil.getProjectId()));
//            if ("project_id".equals(columnStr)) {
//                equalsTo.setRightExpression(new LongValue(ContextUtil.getProjectId()));
//            } else if ("subsystem_id".equals(columnStr)) {
//                equalsTo.setRightExpression(new LongValue(ContextUtil.getSubSystemId()));
//            } else if ("team_id".equals(columnStr)) {
//                equalsTo.setRightExpression(new LongValue(ContextUtil.getTeamId()));
//            }
//        }
//        if (null != where) {
//            return where instanceof OrExpression ? new AndExpression(equalsTo, new Parenthesis(where)) : new AndExpression(equalsTo, where);
//        } else {
//            return equalsTo;
//        }
//    }
//
//    protected void processInsertSelect(SelectBody selectBody) {
//        PlainSelect plainSelect = (PlainSelect) selectBody;
//        FromItem fromItem = plainSelect.getFromItem();
//        if (fromItem instanceof Table) {
//            Table fromTable = (Table) fromItem;
//            plainSelect.setWhere(this.builderExpression(plainSelect.getWhere(), fromTable));
//            this.appendSelectItem(plainSelect.getSelectItems());
//        } else if (fromItem instanceof SubSelect) {
//            SubSelect subSelect = (SubSelect) fromItem;
//            this.appendSelectItem(plainSelect.getSelectItems());
//            this.processInsertSelect(subSelect.getSelectBody());
//        }
//
//    }
//
//    protected void appendSelectItem(List<SelectItem> selectItems) {
//        if (!CollectionUtils.isEmpty(selectItems)) {
//            if (selectItems.size() == 1) {
//                SelectItem item = (SelectItem) selectItems.get(0);
//                if (item instanceof AllColumns || item instanceof AllTableColumns) {
//                    return;
//                }
//            }
//
//            selectItems.add(new SelectExpressionItem(new Column("tenant_id")));
//        }
//    }
//
//    protected void processPlainSelect(PlainSelect plainSelect) {
//        FromItem fromItem = plainSelect.getFromItem();
//        Expression where = plainSelect.getWhere();
//        this.processWhereSubSelect(where);
//        if (fromItem instanceof Table) {
//            Table fromTable = (Table) fromItem;
////            if (!this.tenantLineHandler.ignoreTable(fromTable.getName())) {
//            plainSelect.setWhere(this.builderExpression(where, fromTable));
////            }
//        } else {
//            this.processFromItem(fromItem);
//        }
//
//        List<Join> joins = plainSelect.getJoins();
//        if (joins != null && joins.size() > 0) {
//            joins.forEach((j) -> {
//                this.processJoin(j);
//                this.processFromItem(j.getRightItem());
//            });
//        }
//
//    }
//
//    protected void processWhereSubSelect(Expression where) {
//        if (where != null) {
//            if (where instanceof FromItem) {
//                this.processFromItem((FromItem) where);
//            } else {
//                if (where.toString().indexOf("SELECT") > 0) {
//                    if (where instanceof BinaryExpression) {
//                        BinaryExpression expression = (BinaryExpression) where;
//                        this.processWhereSubSelect(expression.getLeftExpression());
//                        this.processWhereSubSelect(expression.getRightExpression());
//                    } else if (where instanceof InExpression) {
//                        InExpression expression = (InExpression) where;
//                        ItemsList itemsList = expression.getRightItemsList();
//                        if (itemsList instanceof SubSelect) {
//                            this.processSelectBody(((SubSelect) itemsList).getSelectBody());
//                        }
//                    } else if (where instanceof ExistsExpression) {
//                        ExistsExpression expression = (ExistsExpression) where;
//                        this.processWhereSubSelect(expression.getRightExpression());
//                    } else if (where instanceof NotExpression) {
//                        NotExpression expression = (NotExpression) where;
//                        this.processWhereSubSelect(expression.getExpression());
//                    } else if (where instanceof Parenthesis) {
//                        Parenthesis expression = (Parenthesis) where;
//                        this.processWhereSubSelect(expression.getExpression());
//                    }
//                }
//
//            }
//        }
//    }
//
//    protected void processFromItem(FromItem fromItem) {
//        if (fromItem instanceof SubJoin) {
//            SubJoin subJoin = (SubJoin) fromItem;
//            if (subJoin.getJoinList() != null) {
//                subJoin.getJoinList().forEach(this::processJoin);
//            }
//
//            if (subJoin.getLeft() != null) {
//                this.processFromItem(subJoin.getLeft());
//            }
//        } else if (fromItem instanceof SubSelect) {
//            SubSelect subSelect = (SubSelect) fromItem;
//            if (subSelect.getSelectBody() != null) {
//                this.processSelectBody(subSelect.getSelectBody());
//            }
//        } else if (fromItem instanceof ValuesList) {
//            this.logger.debug("Perform a subquery, if you do not give us feedback");
//        } else if (fromItem instanceof LateralSubSelect) {
//            LateralSubSelect lateralSubSelect = (LateralSubSelect) fromItem;
//            if (lateralSubSelect.getSubSelect() != null) {
//                SubSelect subSelect = lateralSubSelect.getSubSelect();
//                if (subSelect.getSelectBody() != null) {
//                    this.processSelectBody(subSelect.getSelectBody());
//                }
//            }
//        }
//
//    }
//
//    protected void processJoin(Join join) {
//        if (join.getRightItem() instanceof Table) {
//            Table fromTable = (Table) join.getRightItem();
////            if (this.tenantLineHandler.ignoreTable(fromTable.getName())) {
////                return;
////            }
//
//            join.setOnExpression(this.builderExpression(join.getOnExpression(), fromTable));
//        }
//
//    }
//
//    protected Expression builderExpression(Expression currentExpression, Table table) {
//        //存在sql套sql情况，所以需要在校验一遍表
//        if(TenantIgnoreTable.baseTable.contains(table.getName())){
//            return currentExpression;
//        }
//        EqualsTo equalsTo = new EqualsTo();
//        equalsTo.setLeftExpression(this.getAliasColumn(table));
//        equalsTo.setRightExpression(new LongValue(ContextUtil.getProjectId()));
//        String tableName = table.getName();
//        if (isEqualsNoNull(tableName)) {
//            //值为空，则不走判断
//            equalsTo.setLeftExpression(new Column("project_id"));
//            equalsTo.setRightExpression(new LongValue(ContextUtil.getProjectId()));
//        } else {
//            String columnStr = DataScopeHandler.queryTenantField(DataScopeHandler.queryTenantSystemScope(tableName));
//            if ("project_id".equals(columnStr)) {
//                equalsTo.setRightExpression(new LongValue(ContextUtil.getProjectId()));
//            } else if ("subsystem_id".equals(columnStr)) {
//                equalsTo.setRightExpression(new LongValue(ContextUtil.getSubSystemId()));
//            } else if ("team_id".equals(columnStr)) {
//                equalsTo.setRightExpression(new LongValue(ContextUtil.getTeamId()));
//            }
//        }
//        if (currentExpression == null) {
//            return equalsTo;
//        } else {
//            return currentExpression instanceof OrExpression ? new AndExpression(new Parenthesis(currentExpression), equalsTo) : new AndExpression(currentExpression, equalsTo);
//        }
//    }
//
//    /**
//     * 判断值是否为空，做个回路判断，遇到定时器之内的操作，需要处理
//     * 定时器不走http请求
//     *
//     * @param tableName
//     * @return
//     */
//    public Boolean isEqualsNoNull(String tableName) {
//        String columnStr = DataScopeHandler.queryTenantField(DataScopeHandler.queryTenantSystemScope(tableName));
//        if ("project_id".equals(columnStr)) {
//            if (ContextUtil.getProjectId() == null) {
//                return true;
//            }
//        } else if ("subsystem_id".equals(columnStr)) {
//            if (ContextUtil.getSubSystemId() == null) {
//                return true;
//            }
//        } else if ("team_id".equals(columnStr)) {
//            if (ContextUtil.getTeamId() == null) {
//                return true;
//            }
//        }
//        return false;
//    }
//
//    protected Column getAliasColumn(Table table) {
//        String tableName = table.getName();
//        //数据隔离级别
//        String columnStr = DataScopeHandler.queryTenantField(DataScopeHandler.queryTenantSystemScope(tableName));
//        StringBuilder column = new StringBuilder();
//        if (table.getAlias() != null) {
//            column.append(table.getAlias().getName()).append(".");
//        }
//        column.append(columnStr);
//        return new Column(column.toString());
//    }
//
//
//}
